package com.tanhua.dubbo.api;

import com.tan.model.mongo.Video;
import com.tan.model.mongo.VideoComment;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class VideocommentApiimpl implements VideocommentApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void saveVideoComments(String videoid, String comment, Long userid) {
        VideoComment videoComment = new VideoComment();
        Criteria criteria=Criteria.where("id").is(videoid);
        Query query=new Query(criteria);
        Video video =  mongoTemplate.findOne(query,Video.class);
        videoComment.setVideoObjectId(video.getId());
        videoComment.setUserId(userid);
        videoComment.setContent(comment);
        videoComment.setVId(video.getVid());
        videoComment.setCreated(System.currentTimeMillis());
        mongoTemplate.save(videoComment);
       Criteria criteria1=Criteria.where("id").is(videoid);
       Query query1=new Query(criteria1);
       Update update=new Update();
       update.inc("commentCount",1);
       mongoTemplate.updateFirst(query1,update,Video.class);

    }

    @Override
    public List<VideoComment> queryVideoComments(String videoid, Integer page, Integer pagesize) {
        ObjectId id = new ObjectId(videoid);
        Criteria criteria=Criteria.where("VideoObjectId").is(id);
        Query query=new Query(criteria);
        query.with(Sort.by(Sort.Direction.DESC,"created")).limit(pagesize).skip((page-1)*pagesize);
        List<VideoComment> videoCommentList = mongoTemplate.find(query, VideoComment.class);
        if (videoCommentList!=null){
            return videoCommentList;
        }
        return null;
    }

    @Override
    public void likeVideoComments(String id) {
        Criteria criteria=Criteria.where("id").is(id);
        Query query=new Query(criteria);
        Update update=new Update();
        update.inc("likeCount",1);
        mongoTemplate.updateFirst(query,update,VideoComment.class);
    }

    @Override
    public void dislikeVideoComments(String id) {
        Criteria criteria=Criteria.where("id").is(id);
        Query query=new Query(criteria);
        Update update=new Update();
        update.inc("likeCount",-1);
        mongoTemplate.updateFirst(query,update,VideoComment.class);
    }
}
